package com.yonghui.summer.code.dao.utils;


import com.yonghui.summer.po.MybatisParam;

import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.AnnotationValueVisitor;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;
import java.util.List;
import java.util.Map;

public class ProcessorHelper {


    /**
     * 得到方法参数
     *
     * @param ve
     * @param name
     * @return
     */
    public static MybatisParam getParam(VariableElement ve, String name) {
        MybatisParam mybatisParam = new MybatisParam();
        mybatisParam.setName(name);
        mybatisParam.setArgs(name);
        if (ve.getAnnotation(org.apache.ibatis.annotations.Param.class) != null) {
            mybatisParam.setName(ve.getAnnotation(org.apache.ibatis.annotations.Param.class).value());
            return mybatisParam;
        }


        return mybatisParam;
    }


    public static String setAnnotationValue(
            Map<ExecutableElement, AnnotationValue> values,
            String annotationFiledName, String context) {
        for (Map.Entry<ExecutableElement, AnnotationValue> entry : values
                .entrySet()) {
            if (entry.getKey().getSimpleName()
                    .contentEquals(annotationFiledName)) {

                AnnotationValue av = entry.getValue();
                entry.setValue(new AnnotationValue() {
                    @Override
                    public Object getValue() {
                        return context + av.getValue();
                    }

                    @Override
                    public <R, P> R accept(AnnotationValueVisitor<R, P> v, P p) {
                        return null;
                    }
                });

                return av.getValue().toString();
            }
        }
        return null;
    }


    /**
     * 比较方法是否一致
     *
     * @param src
     * @param dest
     * @return
     */
    public static boolean methodEquals(ExecutableElement src, ExecutableElement dest) {
        if (!src.getSimpleName().toString().equals(dest.getSimpleName().toString())) {
            return false;
        }
        boolean flag = false;
        List<? extends VariableElement> destTpes = dest.getParameters();
        List<? extends VariableElement> srcTpes = src.getParameters();
        int i = 0;
        if (destTpes.size() == srcTpes.size()) {
            if (destTpes.size() == 0) {
                return true;
            }
            for (VariableElement tpe : destTpes) {
                flag = tpe.asType().toString().equals(srcTpes.get(i++).asType().toString());
                if (!flag) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }

    }

}
